﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;

namespace TRPOP.Common
{
    /// <summary>
    /// YorkBaseImageHelper
    /// </summary>
    public class YorkBaseImageHelper
    {
        #region 上传多张图片 UploadImages
        /// <summary>
        ///  上传多张图片
        /// </summary>
        /// <param name="upLoadForder">上传目录，相对于根目录，前不用加"/"</param>
        /// <param name="isResizeImage">是否要压缩</param>
        /// <param name="IsSaveResizeOnly">是否只保存缩略图</param>
        /// <param name="isWaterImage">是否加水印</param>
        /// <param name="oltImageInfo">压缩集合</param>
        /// <param name="maxSize">图片最大限制</param>
        /// <param name="allowImageTypes">允许的图片类型</param>
        /// <returns></returns>
        static public AttachmentInfo[] UploadImages(string upLoadForder, bool isResizeImage, bool IsSaveResizeOnly, bool isWaterImage, List<ImageInfo> oltImageInfo, int maxSize, List<string> allowImageTypes)
        {

            HttpFileCollection uloadCollection = HttpContext.Current.Request.Files;

            //算出文件数量
            int intImageCount = uloadCollection.Count;
            //
            AttachmentInfo[] attachInfos = new AttachmentInfo[intImageCount];

            //循环上传所有的文件
            for (int i = 0; i < intImageCount; i++)
            {
                attachInfos[i] = new AttachmentInfo();

                if (!uloadCollection[i].FileName.Equals(""))
                {
                    //文件名
                    string strFileName = uloadCollection[i].FileName;
                    //文件扩展名
                    string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower();
                    //文件真实类型
                    string strFileType = uloadCollection[i].ContentType;
                    //类型验证 待做

                    //文件大小
                    int intFileSize = uloadCollection[i].ContentLength;
                    if (maxSize > 0)
                    {
                        if (intFileSize > maxSize)
                        {
                            attachInfos[i].ErrorDescription = "对不起，图片上最大不能超过" + maxSize / 1000 + "K，请重新选择上传！";//2010-05-31 梁伟 将提示信息中的maxSize 改成maxSize/1000
                        }
                        else
                        {
                            attachInfos[i] = UploadImage(uloadCollection[i], upLoadForder, isResizeImage, IsSaveResizeOnly, isWaterImage, oltImageInfo);
                        }
                    }
                    else
                    {
                        attachInfos[i] = UploadImage(uloadCollection[i], upLoadForder, isResizeImage, IsSaveResizeOnly, isWaterImage, oltImageInfo);
                    }

                }
            }
            return attachInfos;
        }
        #endregion

        #region 上传单个图片 UploadImage
        /// <summary>
        /// 上传单个图片
        /// </summary>
        /// <param name="postedFile">上传控件</param>
        /// <param name="upLoadForder">上传目录，相对于根目录，前不用加"/"</param>
        /// <param name="isResizeImage">是否需要缩放</param>
        /// <param name="isSaveResizeOnly">是否只保存缩略图</param>
        /// <param name="isWaterImage">是否需要加水印</param>
        /// <param name="oltImageInfo">缩放集合</param>
        /// <returns></returns>
        static public AttachmentInfo UploadImage(HttpPostedFile postedFile, string upLoadForder, bool isResizeImage, bool isSaveResizeOnly, bool isWaterImage, List<ImageInfo> oltImageInfo)
        {
            AttachmentInfo oaiInfo = new AttachmentInfo();
            string strRootFolder = "/";
            //文件名
            string strFileName = postedFile.FileName;
            //文件扩展名
            string strFileExtendName = strFileName.Substring(strFileName.LastIndexOf(".") + 1).ToLower();
            //文件真实类型
            string strFileType = postedFile.ContentType;
            //文件大小
            int intFileSize = postedFile.ContentLength;
            //建立新的时间文件文件夹
            string strNowFolder = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
            //文件上传的文件夹目录（绝对路径）
            string strFolderMapPath;
            if (!upLoadForder.Equals(""))
            {
                strFolderMapPath = Util.GetMapPath(strRootFolder + upLoadForder + "/" + strNowFolder.ToString());
            }
            else
            {
                strFolderMapPath = Util.GetMapPath(strRootFolder + strNowFolder.ToString());
            }
            //取当前时间的字符串                    
            string strNowTimeString = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            //文件的新名称
            string strNewFileName = strNowTimeString + intFileSize.ToString() + "." + strFileExtendName;
            //最终保存文件的路径
            string strFileMapPath = strFolderMapPath + "/" + strNewFileName;
            //返回的文件虚拟目录(相对路径)
            string strFileUploadPath = upLoadForder + "/" + strNowFolder.ToString() + "/" + strNewFileName;
            try
            {
                //加上类型判断(判断是否为系统允许的上传类型,判断文件大小) 
                Directory.CreateDirectory(strFolderMapPath);
                //如果需要缩放
                if (isResizeImage && oltImageInfo != null)
                {

                    //如果只保存缩略图
                    if (isSaveResizeOnly)
                    {
                        foreach (ImageInfo info in oltImageInfo)
                        {
                            string strResizeFileMapPath;

                            if (info.SaveExtendName.Equals(string.Empty))
                            {
                                strResizeFileMapPath = strFileMapPath;
                            }
                            else
                            {
                                strResizeFileMapPath = GetResizeFilePath(strFileMapPath, info.SaveExtendName);
                            }
                            if (info.IsAbsoluteResize)
                                ResizeImageAbsolute(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                            else
                                ResizeImage(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                        }

                    } //保存缩略图和原图
                    else
                    {
                        //如果需要加水印
                        if (isWaterImage)
                        {
                            DrawWaterImage(postedFile.InputStream, strFileMapPath);
                        }
                        else
                        {
                            //保存原图
                            postedFile.SaveAs(strFileMapPath);
                        }
                        //保存缩略图

                        foreach (ImageInfo info in oltImageInfo)
                        {
                            string strResizeFileMapPath;

                            if (info.SaveExtendName.Equals(string.Empty))
                            {
                                strResizeFileMapPath = strFileMapPath;
                            }
                            else
                            {
                                strResizeFileMapPath = GetResizeFilePath(strFileMapPath, info.SaveExtendName);
                            }
                            if (info.IsAbsoluteResize)
                                ResizeImageAbsolute(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                            else
                                ResizeImage(postedFile.InputStream, strResizeFileMapPath, info.Width, info.Height);
                        }
                    }
                }
                else//不需要缩放
                {
                    //如果需要加水印
                    if (isWaterImage)
                    {
                        //保存加完水印的图
                        DrawWaterImage(postedFile.InputStream, strFileMapPath);
                    }
                    else
                    {
                        //保存原图
                        postedFile.SaveAs(strFileMapPath);
                    }
                }
            }
            catch
            {
                oaiInfo.ErrorDescription = "上传图片过程出现故障";
            }
            //HttpContext.Current.Response.Write(strFileUploadPath);
            //附件属性
            oaiInfo.FileName = strRootFolder + strFileUploadPath;
            oaiInfo.FileSize = intFileSize;
            oaiInfo.Attachment = strFileName.Substring(strFileName.LastIndexOf('\\') + 1);
            oaiInfo.FileType = strFileExtendName;
            return oaiInfo;
        }
        #endregion

        #region 等比缩放 用白色填充空白 ResizeImageAbsolute
        /// <summary>
        /// 等比缩放 用白色填充空白
        /// </summary>
        /// <param name="imageStream">图片流</param>
        /// <param name="strSavePath">保存路径</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        public static bool ResizeImageAbsolute(Stream imageStream, string strSavePath, int width, int height)
        {

            bool blnRtn = false;
            try
            {
                //创建图片对象
                //System.Drawing.Image.GetThumbnailImageAbort callb = null;
                Image image;
                //获得图片源
                image = System.Drawing.Image.FromStream(imageStream);


                //计算图片的宽度和高度
                double dobWidth = image.Width;
                double dobHeight = image.Height;


                //重新计算图片等比缩放后的宽度和高度

                if (dobWidth > width || dobHeight > height)
                {
                    if (dobWidth > dobHeight)
                    {
                        dobHeight = (int)(dobHeight * (width / dobWidth));
                        dobWidth = width;

                        if (dobHeight > height)
                        {
                            dobWidth = (int)(dobWidth * (height / dobHeight));
                            dobHeight = height;
                        }
                    }
                    else
                    {
                        dobWidth = (int)(dobWidth * (height / dobHeight));
                        dobHeight = height;
                        if (dobWidth > width)
                        {
                            dobHeight = (int)(dobHeight * (width / dobWidth));
                            dobWidth = width;
                        }
                    }
                }
                Bitmap bitmap = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(bitmap);


                //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //下面这个也设成高质量 
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                //下面这个设成High 
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //把原始图像绘制成上面所设置宽高的缩小图 




                //计算画框的宽度高度以及位置
                //float rectWidth = resizeimage.Width;
                //float rectHeight = resizeimage.Height;
                float rectX = (width - (int)dobWidth) / 2;
                float rectY = (height - (int)dobHeight) / 2;


                System.Drawing.Brush b = new SolidBrush(Color.White);

                Rectangle oreBackRect = new Rectangle(new Point(0, 0), new Size(width, height));//背景颜色

                g.FillRectangle(b, oreBackRect);
                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle((int)rectX, (int)rectY, (int)dobWidth, (int)dobHeight);

                g.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                //保存图片
                bitmap.Save(strSavePath, ImageFormat.Jpeg);

                //释放对象
                g.Dispose();
                bitmap.Dispose();
                //释放image对象的资源
                image.Dispose();
                //释放resizeimage对象的资源
                //resizeimage.Dispose();
                blnRtn = true;
            }
            catch
            {
                blnRtn = false;
            }
            return blnRtn;

        }
        #endregion

        #region  等比缩放 ResizeImage
        /// <summary>
        /// 等比缩放
        /// </summary>
        /// <param name="imageStream">图片流</param>
        /// <param name="strSavePath">保存路径</param>
        /// <param name="width">宽度</param>
        /// <param name="height"></param>
        /// <returns></returns>
        public static bool ResizeImage(Stream imageStream, string strSavePath, int width, int height)
        {

            bool blnRtn = false;
            try
            {
                //创建图片对象
                System.Drawing.Image image;
                //获得图片源
                image = System.Drawing.Image.FromStream(imageStream);
                //计算图片的宽度和高度
                double dobWidth = image.Width;
                double dobHeight = image.Height;
                //重新计算图片等比缩放后的宽度和高度
                if (dobWidth > width || dobHeight > height)
                {

                    if (width == 0 || height == 0)
                    {
                        if (width == 0 && height == 0)
                        {

                        }
                        else if (width == 0)
                        {
                            if (dobHeight > height)
                            {
                                dobWidth = (int)(dobWidth * (height / dobHeight));
                                dobHeight = height;
                            }
                        }
                        else
                        {
                            if (dobWidth > width)
                            {
                                dobHeight = (int)(dobHeight * (width / dobWidth));
                                dobWidth = width;
                            }
                        }

                    }

                    else
                    {

                        if (dobWidth > dobHeight)
                        {
                            dobHeight = (int)(dobHeight * (width / dobWidth));
                            dobWidth = width;

                            if (dobHeight > height)
                            {
                                dobWidth = (int)(dobWidth * (height / dobHeight));
                                dobHeight = height;
                            }
                        }
                        else
                        {
                            dobWidth = (int)(dobWidth * (height / dobHeight));
                            dobHeight = height;
                            if (dobWidth > width)
                            {
                                dobHeight = (int)(dobHeight * (width / dobWidth));
                                dobWidth = width;
                            }
                        }
                    }
                    Bitmap bmp = new Bitmap((int)dobWidth, (int)dobHeight);
                    //从Bitmap创建一个System.Drawing.Graphics对象，用来绘制高质量的缩小图。 
                    System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp);
                    //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality 
                    gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
                    //下面这个也设成高质量 
                    gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
                    //下面这个设成High 
                    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                    //把原始图像绘制成上面所设置宽高的缩小图 
                    System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, (int)dobWidth, (int)dobHeight);
                    gr.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

                    bmp.Save(strSavePath);
                    bmp.Dispose();
                    image.Dispose();
                }
                else
                {
                    //保存图片
                    image.Save(strSavePath);
                    //释放image对象的资源
                    image.Dispose();
                }

                blnRtn = true;
            }
            catch
            {
                blnRtn = false;
            }
            return blnRtn;

        }

        #endregion

        #region 获取缩略图地址 GetResizeFilePath
        /// <summary>
        /// 获取缩略图地址
        /// </summary>
        /// <param name="strFilePath">图片名</param>
        /// <param name="strExtendName">缩略图扩展名</param>
        /// <returns></returns>
        static public string GetResizeFilePath(string strFilePath, string strExtendName)
        {
            string strRtn;
            string strTemp;
            string regex = @"/([0-9]{1,})\.";
            Regex re = new Regex(regex);
            Match m = re.Match(strFilePath);

            if (m.Success)
            {
                strTemp = m.Result("$1") + "_" + strExtendName;
                strRtn = strFilePath.Replace(m.Result("$1"), strTemp);
            }
            else
            {
                strRtn = strFilePath;
            }
            return strRtn;
        }
        #endregion

        #region 加水印 DrawWaterImage
        /// <summary>
        ///  加水印
        /// </summary>
        /// <param name="imageStream">图片流</param>
        /// <param name="strSavePath">保存路径</param>
        /// <returns></returns>
        private static bool DrawWaterImage(Stream imageStream, string strSavePath)
        {
            bool blnRtn = false;
            try
            {

                //获得图片源和水印图片源
                System.Drawing.Image image = System.Drawing.Image.FromStream(imageStream);
                System.Drawing.Image imageWater = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("/watermark.png"));

                //根据图片源创建BitMap
                Bitmap bitmap = new Bitmap(image, image.Width, image.Height);
                Graphics g = Graphics.FromImage(bitmap);


                //计算画框的宽度高度以及位置
                float rectWidth = imageWater.Width;
                float rectHeight = imageWater.Height;
                float rectX = image.Width - imageWater.Width;
                float rectY = image.Height - imageWater.Height;

                //加上水印
                g.DrawImage(imageWater, rectX, rectY, rectWidth, rectHeight);


                //释放对象
                image.Dispose();
                imageWater.Dispose();

                //保存图片
                bitmap.Save(strSavePath, ImageFormat.Jpeg);

                //释放对象
                g.Dispose();
                bitmap.Dispose();
            }
            catch
            {
                blnRtn = false;
            }
            return blnRtn;
        }
        #endregion
    }
}
